import pymysql
from pyecharts.charts import Pie
from pyecharts import options

# 连接数据库.
db = pymysql.connect(
    host="localhost",
    user="root",
    password="123456",
    database="crawlerdemo",
    charset='utf8'
)
# 获取游标.
cursor = db.cursor()

sql = "select count(job_id),job_place from job group by job_place order by count(job_id) desc limit 5"

try:
    cursor.execute(sql)
    res = cursor.fetchall()
    # 计算查询结果中所有城市的岗位数量
    sum=0
    for i in res:
       sum+=i[0]
    # 计算每个城市的占比情况.
    res_list=[]
    for i in res:
        res_yuanzu=()
        res_yuanzu=(i[1],i[0]/sum*100,)
        res_list.append(res_yuanzu)
    # 创建饼状图对象
    print(res_list)
    pie=Pie()
    pie.add("百分比%",res_list)
    pie.set_global_opts(title_opts=options.TitleOpts(title="岗位数量最多的五个城市的岗位数量占比",subtitle="单位:百分比%"))
    pie.render("piera.html")
except:
    print("查询有误")